package top.rainf.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import top.rainf.constants.AttributeConstants;
import top.rainf.support.Result;
import top.rainf.support.VerifyCodeGenerator;
import top.rainf.util.CookieSetter;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author 星环
 * @date 2023/5/6 17:33:13
 * @description 验证码控制器
 */
@Controller
//@CrossOrigin
@RequestMapping("/captcha")
public class CaptchaController {

    /**
     * 生成验证码图片，传递给浏览器
     * 部分使用方法参考自若依框架
     * @param request
     * @param response
     * @return
     */
    @GetMapping(value = "/captchaImage")
    public Result getCaptchaImage(HttpServletRequest request, HttpServletResponse response)
    {
        CookieSetter cookieSetter = new CookieSetter(request,response);

        //设置响应头，参自若依，是用来表明这是什么的
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");
        //生成要绘制的验证码
        String code = VerifyCodeGenerator.generateVerifyCode(4);
        //将验证码存入session
        cookieSetter.setSessionAttr(AttributeConstants.REAL_CODE,code);
        //将验证码写入图片
        BufferedImage captcha = VerifyCodeGenerator.generateVerifyCodeImage(code);
        //发送图片给浏览器
        //将图片写入响应体的输出流
        try (ServletOutputStream out = response.getOutputStream()) {
            ImageIO.write(captcha,"png", out);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return Result.success().addObj(AttributeConstants.REAL_CODE,code);
    }


}



